import os

from subprocess import *

def initlog(logfile):
    import logging
    
    logger = logging.getLogger()
    hdlr = logging.FileHandler(logfile)
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    hdlr.setFormatter(formatter)
    logger.addHandler(hdlr)
    logger.setLevel(logging.NOTSET)
    
    return logger

#def extract_packages(package_path, root_path):     
def extract_packages():     
        # Tools required - tar, bunzip2, unzip, ar, zcat, rpm2cpio
        # Command calls should be safe only our generated path names are passed in

        # change the working folder
        soft_name = raw_input("please input the soft name:")
        root_path = raw_input("please input the working folder:")
        os.chdir(root_path)
#        os.makedirs(soft_name+"/usr/lib")
        os.chdir(soft_name)
        
        package_path = raw_input("please input the package path:")
        
	execute_extract_command("pack %s %s %s 1024" %(soft_name,os.path.join(root_path,soft_name),package_path))
        # Zip archives
#        execute_extract_command("UNP=$(find %s/*.tgz 2>/dev/null) && for UN in $UNP; do tar zxvf $UN ; done" % (package_path))
#        execute_extract_command("UNP=$(find %s/*.tar.gz 2>/dev/null) && for UN in $UNP; do tar zxvf $UN ; done" % (package_path))
#        execute_extract_command("UNP=$(find %s/*.tbz 2>/dev/null) && for UN in $UNP; do bunzip2 -c $UN | tar -xvf - ; done" % (package_path))
#        execute_extract_command("UNP=$(find %s/*.tar.bz2 2>/dev/null) && for UN in $UNP; do bunzip2 -c $UN | tar -xvf - ; done" % (package_path))
#        execute_extract_command("UNP=$(find %s/*.tbz2 2>/dev/null) && for UN in $UNP; do bunzip2 -c $UN | tar -xvf - ; done" % (package_path))
#        execute_extract_command("UNP=$(find %s/*.zip 2>/dev/null) && for UN in $UNP; do unzip $UN ; done" % (package_path))
                
        # Debain packages
#        execute_extract_command("UNP=$(find %s/*.deb 2>/dev/null) && for UN in $UNP; do ar p $UN data.tar.gz | zcat | tar xv ; done" % (package_path))   
                
        # RPM packages
        # TODO: we need a better rpm extra
        # http://www.rpm.org/max-rpm/s1-rpm-file-format-rpm-file-format.html
#        execute_extract_command("UNP=$(find %s/*.rpm 2>/dev/null) && for UN in $UNP; do rpm2cpio < $UN | cpio -i -d --verbose ; done" % (package_path))
                
def execute_extract_command(command):
        p = Popen(command, stdout=PIPE, shell=True, stderr=STDOUT)
        for line in p.stdout:
            logger.info(line.split("\n"))
        p.stdout.close()
        p.wait()
        
if __name__ == "__main__":
        logger = initlog("/tmp/extract.log")
        extract_packages()
        
